import { NavBar, Card, Button, Tag, Toast } from 'antd-mobile'
import { useEffect, useState } from 'react'
import { useNavigate, useParams } from 'react-router-dom'
import styles from './index.module.css'
import { fetchReceptionDetail, uploadFile, confirmReception } from '../../services/api'
import iconYes from '../../assets/check_yes.svg'
import iconNo from '../../assets/check_no.svg'
import iconNone from '../../assets/no_check.svg'
import iconNoneNo from '../../assets/no_check_no.svg'

export default function FacilityInfo() {
  const navigate = useNavigate()
  const { id } = useParams()
  const [detail, setDetail] = useState<any>(null)
  const pickImage = async () => {
    return await new Promise<File[]>(resolve => {
      const input = document.createElement('input')
      input.type = 'file'
      input.accept = 'image/*'
      input.multiple = true
      ;(input as any).capture = 'environment'
      input.onchange = () => {
        resolve(Array.from(input.files || []))
      }
      input.click()
    })
  }
  const handlePick = async (target: any) => {
    const files = await pickImage()
    if (!files || files.length === 0) return
    try {
      const proxy = (import.meta as any).env?.VITE_PROXY_TARGET as string | undefined
      const results = await Promise.all(
        files.map(async f => {
          try {
            const res = await uploadFile(f)
            const url = proxy ? `${proxy}${res.link || ''}` : res.link
            const name = res.originalName || res.name || f.name
            return { name, url, link: res.link }
          } catch {
            return null
          }
        }),
      )
      const ok = results.filter(Boolean) as Array<{ name: string; url: string; link?: string }>
      if (ok.length) {
        target._tempFiles = Array.isArray(target._tempFiles) ? target._tempFiles : []
        target._tempFiles.push(...ok)
        setDetail({ ...detail })
      }
      Toast.show({
        icon: ok.length ? 'success' : 'fail',
        content: ok.length ? `上传成功${ok.length}张` : '上传失败',
      })
    } catch (e) {
      Toast.show({ icon: 'fail', content: '上传失败' })
    }
  }

  const buildFiles = (item: any) => {
    if (Array.isArray(item?._tempFiles) && item._tempFiles.length > 0) {
      return item._tempFiles
        .map((f: any) => f.link || f.url || '')
        .filter((s: string) => !!s)
        .join(',')
    }
    return item?.files || ''
  }

  const buildPayload = () => {
    const mapItem = (it: any) => ({
      id: detail?.id ?? '',
      houseId: detail?.houseId ?? '',
      receptionId: it?.receptionId ?? '',
      name: it?.name ?? '',
      type: it?.type ?? 0,
      remark: it?.remark ?? '',
      state: typeof it?.state === 'number' ? it.state : 0,
      files: buildFiles(it),
    })
    const houseSituations = Array.isArray(detail?.houseSituations)
      ? detail.houseSituations.map(mapItem)
      : []
    const furnitureSituations = Array.isArray(detail?.furnitureSituations)
      ? detail.furnitureSituations.map(mapItem)
      : []
    const payload = { id, houseSituations, furnitureSituations, facilityVerification: 1 }
    // eslint-disable-next-line no-console
    console.log('Facility submit payload:', payload)
    return payload
  }

  const removeTempFile = (target: any, url: string) => {
    const list = Array.isArray(target._tempFiles) ? target._tempFiles : []
    target._tempFiles = list.filter((f: any) => f.url !== url)
    setDetail({ ...detail })
  }

  useEffect(() => {
    if (!id) return
    fetchReceptionDetail(id)
      .then(setDetail)
      .catch(() => null)
  }, [id])

  return (
    <div className={styles['facility-page']}>
      <NavBar back onBack={() => navigate(-1)}>
        设施信息
      </NavBar>

      <div className={styles['facility-section']}>
        <Card style={{ borderRadius: 12 }}>
          <div className={styles['facility-header']}>
            <div className={styles['facility-title']}>
              {detail?.buildingEstateName || detail?.projectName || '—'}
              <span className={styles['facility-sub']}>
                {detail?.houseNo ? `-${detail.houseNo}` : ''}
              </span>
            </div>
            <div className={styles['facility-tags']}>
              <Tag
                color="primary"
                fill="outline"
                style={{ padding: '0 8px', height: 22, lineHeight: '22px' }}
              >
                {detail?.buildingUnitName || '—'}
              </Tag>
              <Tag
                color="primary"
                fill="outline"
                style={{ padding: '0 8px', height: 22, lineHeight: '22px' }}
              >
                {detail?.houseNo || '—'}
              </Tag>
            </div>
          </div>
          <div className={styles['facility-divider']}>房屋基本情况</div>
          {(detail?.houseSituations || []).map((it: any, idx: number) => (
            <div className={styles['facility-row']} key={idx}>
              <span className={styles['facility-left']}>
                <span className={styles['facility-name']}>{it.name || '-'}</span>
                <span className={styles['facility-left-col']}>
                  <a className={styles['facility-link']} onClick={() => handlePick(it)}>
                    上传附件
                  </a>
                  {Array.isArray(it._tempFiles) && it._tempFiles.length > 0 && (
                    <div className={styles['facility-thumbs']}>
                      {it._tempFiles.map((f: any, i: number) => (
                        <div key={f.url || i} className={styles['facility-thumb']}>
                          <img
                            className={styles['facility-thumb-img']}
                            src={f.url}
                            alt={f.name}
                            onClick={() => window.open(f.url, '_blank')}
                          />
                          <div
                            className={styles['facility-thumb-del']}
                            onClick={() => removeTempFile(it, f.url)}
                          >
                            ×
                          </div>
                        </div>
                      ))}
                    </div>
                  )}
                </span>
              </span>
              <span className={styles['verify-pair']}>
                <img
                  src={it.state === 1 ? iconYes : iconNone}
                  className={`${styles['verify-icon']} ${styles['clickable']}`}
                  onClick={() => {
                    it.state = 1
                    setDetail({ ...detail })
                  }}
                />
                <img
                  src={it.state === 0 ? iconNo : iconNoneNo}
                  className={`${styles['verify-icon']} ${styles['clickable']}`}
                  onClick={() => {
                    it.state = 0
                    setDetail({ ...detail })
                  }}
                />
              </span>
            </div>
          ))}

          <div className={styles['facility-divider']}>家具情况</div>
          {(detail?.furnitureSituations || []).map((it: any, idx: number) => (
            <div className={styles['facility-row']} key={idx}>
              <span className={styles['facility-left']}>
                <span className={styles['facility-name']}>{it.name || '-'}</span>
                <span className={styles['facility-left-col']}>
                  <a className={styles['facility-link']} onClick={() => handlePick(it)}>
                    上传附件
                  </a>
                  {Array.isArray(it._tempFiles) && it._tempFiles.length > 0 && (
                    <div className={styles['facility-thumbs']}>
                      {it._tempFiles.map((f: any, i: number) => (
                        <div key={f.url || i} className={styles['facility-thumb']}>
                          <img
                            className={styles['facility-thumb-img']}
                            src={f.url}
                            alt={f.name}
                            onClick={() => window.open(f.url, '_blank')}
                          />
                          <div
                            className={styles['facility-thumb-del']}
                            onClick={() => removeTempFile(it, f.url)}
                          >
                            ×
                          </div>
                        </div>
                      ))}
                    </div>
                  )}
                </span>
              </span>
              <span className={styles['verify-pair']}>
                <img
                  src={it.state === 1 ? iconYes : iconNone}
                  className={`${styles['verify-icon']} ${styles['clickable']}`}
                  onClick={() => {
                    it.state = 1
                    setDetail({ ...detail })
                  }}
                />
                <img
                  src={it.state === 0 ? iconNo : iconNoneNo}
                  className={`${styles['verify-icon']} ${styles['clickable']}`}
                  onClick={() => {
                    it.state = 0
                    setDetail({ ...detail })
                  }}
                />
              </span>
            </div>
          ))}
        </Card>
      </div>

      <div className={styles['facility-bottom']}>
        <Button
          size="large"
          style={{ fontSize: '14px' }}
          className={styles['facility-btn'] + ' ' + styles['ghost']}
          onClick={() => navigate(-1)}
        >
          取消
        </Button>
        <Button
          size="large"
          style={{ fontSize: '14px' }}
          className={styles['facility-btn'] + ' ' + styles['primary']}
          onClick={async () => {
            const payload = buildPayload()
            try {
              await confirmReception(payload)
              Toast.show({ icon: 'success', content: '已完成设施核验' })
              navigate(-1)
            } catch (e) {
              // 失败提示已在拦截器处理
            }
          }}
        >
          完成
        </Button>
      </div>
    </div>
  )
}
